package ppa.marc.importer;

import java.io.File;
import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;

@Component
public class JsapBasedArgumentParser implements ArgumentParser {
	private final JSAP jsap;
	private File filename;

	@Autowired
	public JsapBasedArgumentParser(JSAP jsap) throws JSAPException {
		this.jsap = jsap;
		jsap.registerParameter(JsapParameters.INPUT_FILE);
	}

	@Override
	public void parseArguments(String[] commandLineArguments) throws IllegalArgumentException {
		JSAPResult jsapResult = jsap.parse(commandLineArguments);
		if(!jsapResult.success()) {
			throw new IllegalArgumentException(extractErrorMessage(jsapResult));
		}
		else {
			filename = new File(jsapResult.getString(JsapParameters.INPUT_FILE.getID()));
		}
	}

	private String extractErrorMessage(JSAPResult jsapResult) {
		@SuppressWarnings("rawtypes")
		Iterator it = jsapResult.getErrorMessageIterator();
		StringBuffer errorMessage = new StringBuffer("Incorrect command line arguments:");
		while(it.hasNext()) {
			errorMessage.append(it.next() + "\n");
		}
		return errorMessage.toString();
	}

	@Override
	public File getSourceFile() {
		return filename;
	}
}
